<template>
  <a-modal
    v-model:open="visible"
    title="编辑个人信息"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    width="520px"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
    >
      <a-form-item label="用户名" name="userName">
        <a-input
          v-model:value="formData.userName"
          placeholder="请输入用户名"
          :maxlength="20"
          show-count
        />
      </a-form-item>

      <a-form-item label="头像链接" name="userAvatar">
        <a-input
          v-model:value="formData.userAvatar"
          placeholder="请输入头像链接URL"
        />
        <div class="avatar-preview">
          <a-avatar :size="64" :src="formData.userAvatar || undefined" style="margin-top: 8px;">
            <template v-if="!formData.userAvatar">
              {{ formData.userName?.charAt(0)?.toUpperCase() || 'U' }}
            </template>
          </a-avatar>
        </div>
      </a-form-item>

      <a-form-item label="个人简介" name="userProfile">
        <a-textarea
          v-model:value="formData.userProfile"
          placeholder="请输入个人简介"
          :rows="4"
          :maxlength="200"
          show-count
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { message } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import { updateUser } from '@/api/userController'
import { useLoginUserStore } from '@/stores/LoginUserStore'

const props = defineProps<{
  open: boolean
  userInfo: API.LoginUserVO
}>()

const emit = defineEmits<{
  'update:open': [value: boolean]
  'success': []
}>()

const formRef = ref<FormInstance>()
const loading = ref(false)

const formData = reactive<API.UserUpdateRequest>({
  id: undefined,
  userName: '',
  userAvatar: '',
  userProfile: '',
  userRole: undefined
})

const rules = {
  userName: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度为2-20个字符', trigger: 'blur' }
  ],
  userAvatar: [
    {
      validator: (_rule: any, value: string) => {
        if (!value || value.trim() === '') {
          return Promise.resolve()
        }
        try {
          new URL(value)
          return Promise.resolve()
        } catch {
          return Promise.reject('请输入有效的URL地址')
        }
      },
      trigger: 'blur'
    }
  ],
  userProfile: [
    { max: 200, message: '个人简介最多200个字符', trigger: 'blur' }
  ]
}

const loginUserStore = useLoginUserStore()

// 监听 open 变化，初始化表单数据
watch(() => props.open, (newVal) => {
  if (newVal && props.userInfo) {
    formData.id = props.userInfo.id
    formData.userName = props.userInfo.userName || ''
    formData.userAvatar = props.userInfo.userAvatar || ''
    formData.userProfile = props.userInfo.userProfile || ''
    formData.userRole = props.userInfo.userRole
  }
})

// 计算属性，用于 v-model:open
const visible = computed({
  get: () => props.open,
  set: (val) => emit('update:open', val)
})

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value?.validate()
    loading.value = true

    const res = await updateUser({
      id: formData.id,
      userName: formData.userName,
      userAvatar: formData.userAvatar || undefined,
      userProfile: formData.userProfile || undefined,
      userRole: formData.userRole
    })

    if (res.data.code === 0) {
      message.success('修改成功')
      // 刷新用户信息
      await loginUserStore.fetchLoginUser()
      emit('success')
      visible.value = false
    } else {
      message.error('修改失败：' + res.data.message)
    }
  } catch (error) {
    console.error('表单验证失败', error)
  } finally {
    loading.value = false
  }
}

// 取消
const handleCancel = () => {
  formRef.value?.resetFields()
  visible.value = false
}
</script>


<style scoped>
.avatar-preview {
  margin-top: 8px;
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
}
</style>
